<template>
  <div class="dashboard-editor-container">
    <div
      style="background:#fff;padding:16px;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
      <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset"></connsearch>
      <div>
        <div>
          <el-button type="primary" :disabled="choseList.length === 0" @click="dialogClick(1)">注册选中</el-button>
          <el-button type="danger" :disabled="choseList.length === 0" @click="handleDelete(1)">删除选中</el-button>
        </div>
        <el-table stripe border @selection-change="handleSelectionChange" :data="tableData"
          style="width: 100%;margin-top:20px;">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" :index="calcIndex" width="55"></el-table-column>
          <el-table-column prop="CreateTime" label="发现时间" width="180">
            <template slot-scope="{row}">
              <span> {{ parseTime(row.CreateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="DepartmentID" label="部门" width="120" :formatter=FilterDepartment
            show-overflow-tooltip></el-table-column>
          <el-table-column prop="DeviceCode" label="资产编码" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="DeviceName" label="资产名称" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="DeviceType" label="资产类型" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="Phone" label="手机号码" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="DeviceIP" label="资产地址" width="180"></el-table-column>
          <el-table-column prop="HardID" label="资产mac" width="180"></el-table-column>
          <el-table-column prop="OsInfo" label="操作系统" show-overflow-tooltip width="120px"></el-table-column>
          <el-table-column prop="Factory" label="厂商信息" show-overflow-tooltip width="120px"></el-table-column>
          <!-- <el-table-column prop="OpenPort" label="开放端口" show-overflow-tooltip min-width="80">
            <template slot-scope="{row}">
              <span> {{ row.OpenPort | filterPort }}</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="ComputerName" label="计算机名" show-overflow-tooltip></el-table-column>
          <el-table-column prop="CreateBy" label="发现方式" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span> {{ row.CreateBy | filterCreateBy }}</span>
            </template>
          </el-table-column>
          <el-table-column width="180" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="dialogClick(2, scope.row)">注册</el-button>
              <el-button type="danger" size="mini" @click="handleDelete(2, scope.row)">删除</el-button>
            </template>
          </el-table-column>
          <template slot="empty">
            <div class="empty">
              <svg-icon icon-class="notAvailable" class="notAvailable"></svg-icon>
              <!-- <span>{{imgTitle}}</span> -->
            </div>
          </template>
        </el-table>
        <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page=pageNum :page-size=pageSize
          background layout="total, prev, pager, sizes, next, jumper" :total="total">
        </el-pagination>
      </div>
      <!-- 注册资产弹窗 -->
      <newAssetsAdded title="资产注册" :moderVisible="moderVisible" :Action="Action" :Moder="Moder" @submit="submit"
        @cancel="cancel"></newAssetsAdded>
      <batchRegistration title="批量注册" :moderVisible="batchRegistrationDialog" :Action="Action" :Moder="Moder"
        @submit="submit2" @cancel="cancel2"></batchRegistration>
    </div>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage';
import { toTree } from '@/utils/index.js'
import connsearch from "@/components/connSearch";
import { parseTime, getTreeData } from '@/utils/index';
import newAssetsAdded from "./components/newAssetsAdded"
import batchRegistration from "./components/batchRegistration"
export default {
  components: { connsearch, newAssetsAdded, batchRegistration },
  filters: {
    filterPort(row) {
      return row ? row.join(',') : '-'
    },
    filterCreateBy(Status) {
      const map = {
        1: 'NMAP扫描',
        2: '交换机SNMP',
        3: '管理界面创建',
        4: '主站平台创建',
        5: '镜像口信息发现',
        6: '安装代理自动创建资产',
        7: '通过syslog、snmp、trap创建资产'
      };
      return map[Status];
    }
  },
  data() {
    let that = this
    return {
      imgTitle: '数据加载中，请稍后......',
      choseList: [],
      deleteList: [],//装删除接口需要的参数
      width: '100px',
      moderVisible: false,
      batchRegistrationDialog: false,
      Action: 1,
      Moder: {},
      disabled: true,
      deleteDisabled: true,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      centerDialogVisible: false,
      options: [], //分组数据
      arrayList: [], //装取selection选中数据
      arrayListDel: [],
      DepartmentList: [],
      searchform: {
        DeviceIP: '',
        DeviceMAC: '',
        DeviceName: '',
        DeviceCode: ''
      },
      formOptions: [
        {
          col: 6,
          label: "IP地址/范围", // label文字
          prop: "DeviceIP", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入IP地址/范围,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.DeviceIP = val
            }
          }
        },
        {
          col: 6,
          label: "MAC地址", // label文字
          prop: "DeviceMAC", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入MAC地址,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.DeviceMAC = val
            }
          }
        },
        {
          col: 6,
          label: "资产名称", // label文字
          prop: "DeviceName", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入资产名称,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.DeviceName = val
            }
          }
        },
        {
          col: 6,
          label: "资产编码", // label文字
          prop: "DeviceCode", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入资产编码,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.DeviceCode = val
            }
          }
        }

      ]
    }
  },
  created() {
    this.GetDepartment()
  },
  mounted() { },
  watch: {
    // 监听批量批量注册是否可点击
    arrayList(val) {
      if (val.length === 0) {
        this.deleteDisabled = true;
      } else {
        this.deleteDisabled = false;
      }
    },
    // 监听批量批量删除是否可点击
    arrayListDel(val) {
      if (val.length === 0) {
        this.disabled = true;
      } else {
        this.disabled = false;
      }
    }
  },
  methods: {
    parseTime,
    async GetDepartment() {
      const res = await connrequest('GetDepartment')
      this.DepartmentList = res.Data
      this.getData()
    },
    FilterDepartment(row) {
      return this.DepartmentList.find(item => item.ID === row.DepartmentID)?.DepartmentName || '未知部门'
    },
    // table选中
    handleSelectionChange(val) {
      this.choseList = val
    },
    // 获取未知资产列表
    async getData() {
      this.tableData = [];
      this.imgTitle = '数据加载中，请稍后......'
      const paramData = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          DeviceIP: this.searchform.DeviceIP,
          DeviceMAC: this.searchform.DeviceMAC,
          DeviceName: this.searchform.DeviceName,
          DeviceCode: this.searchform.DeviceCode
        }
      };
      const res = await connrequest('GetUnknownDevice', paramData);
      if (res.Status.StatusCode === 0) {
        if (res.Data.length === 0 && this.pageNum > 1) {
          this.pageNum--
          this.getData();
        } else {
          this.tableData = res.Data;
          this.imgTitle = '抱歉，列表暂无数据......';
          this.total = res.Paging.TotalCount;
        }
      }
    },
    // 删除列表
    async handleDelete(status, row) {
      let deleteList = []
      this.choseList.map(item => {
        deleteList.push(item.DeviceUUID)
      })
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const paramData = {
          Data: status === 1 ? deleteList : [row.DeviceUUID]
        }
        const res = await connrequest('DelUnknownDevice', paramData);
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData();
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async dialogClick(status, row) {
      if (status === 1) {
        this.batchRegistrationDialog = true
        this.Moder = { Role: '员工', StartDate: new Date().getTime() }
        // this.$confirm('是否批量注册选中资产数据?', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(async () => {
        //   const paramData = {
        //     Data: this.choseList
        //   }
        //   const res = await connrequest('RegisterUnknownDevice', paramData);
        //   if (res.Status.StatusCode === 0) {
        //     this.getData();
        //   }
        //   this.$message({
        //     type: 'success',
        //     message: '注册成功!'
        //   });
        // }).catch(() => {
        //   this.$message({
        //     type: 'info',
        //     message: '已取消'
        //   });
        // })
      } else if (status === 2) {
        this.moderVisible = true
        this.Moder = {
          ...row,
          Level: row.Level || 1,
          RealnameType: row.RealnameType || 1,
          RelnameID: row.RelnameID || 1,
          LogLevel: row.LogLevel || 1,
          Role: row.Role || '员工',
          StartDate: new Date().getTime(),
          DepartmentID: row.DepartmentID === 0 ? null : row.DepartmentID
        }
      }
    },
    async getGroupTree() {
      const res = await connrequest('GetDeviceGroup');
      if (res.Status.StatusCode === 0) {
        res.Data.map(item => {
          item.deleteIcon = false
          item.editIcon = false
        })
        this.nodeData = toTree(res.Data)
      }
    },
    async getDeviceType() {
      const data = {
        Filter: {
          Value: 'DeviceType'
        }
      }
      const res = await connrequest('GetDictElem', data)
      this.DeviceTypeList = res.Data.Input.Option
    },
    // 获取标签
    async GetParamTag() {
      const res = await connrequest('GetParamTag')
      this.TagList = res.Data
    },
    // 获取责任人
    async GetDuty() {
      const res = await connrequest('GetDuty')
      this.DutyList = res.Data
    },
    cancel() {
      this.moderVisible = false
    },
    async submit(Moder, Action) {
      const data = {
        Data: [{
          ...Moder,
          StartDate: Math.round(Moder.StartDate / 1000)
        }]
      }
      const res = await connrequest('RegisterUnknownDevice', data)
      if (res.Status.StatusCode === 0) {
        this.$message.success(Action === 1 ? '注册成功' : '修改成功')
        this.moderVisible = false
        this.getData()
      }
    },
    cancel2() {
      this.batchRegistrationDialog = false
    },
    async submit2(Moder) {
      let arr = this.choseList.map(item => {
        item = { ...item, ...Moder, StartDate: Math.round(Moder.StartDate / 1000) }
        return item
      })
      const data = {
        Data: arr
      }
      const res = await connrequest('RegisterUnknownDevice', data)
      if (res.Status.StatusCode === 0) {
        this.$message.success('注册成功')
        this.batchRegistrationDialog = false
        this.getData()
      }
    },
    // 重置
    reset() {
      this.pageNum = 1
      this.formOptions = this.formOptions.map(item => {
        item.initValue = ""
        return item
      })
      this.searchform = {}
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = {}
      this.searchform = { ...val }
      // if(this.searchform.timeRange){
      //   this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      // }
      this.getData()
    },
    // 分页
    currentChange(pageNum) {
      this.pageNum = pageNum;
      this.getData()
    },
    // 条数
    sizeChange(pageSize) {
      this.pageNum = 1;
      this.pageSize = pageSize;
      this.getData()
    },
    calcIndex(index) {
      return (this.pageNum - 1) * this.pageSize + index + 1
    }
  }
}
</script>

<style lang='scss' scoped></style>
